In Svelte, click events are handled using the on:click directive, which allows you to run a function or execute inline code whenever a user clicks an element. This is similar to addEventListener('click', ...) in plain JavaScript but with much cleaner syntax.
Here, when the button is clicked, the increment function runs and updates the count variable. Svelte automatically updates the DOM wherever count is used.
You can also write inline expressions directly inside on:click. In this example, clicking the button directly updates the message variable.
To pass arguments to a function, wrap the call in an arrow function. This prevents the function from running immediately when the component renders.
Use on:click={functionName} to call a function when an element is clicked.
Inline arrow functions can be used for quick logic or to pass arguments.
Svelte automatically handles cleanup — no need to manually remove event listeners.
on:click works with any HTML element, not just buttons.